/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.service.security.impl;

import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PrivateKey;

import javax.crypto.SecretKey;

import cgl.narada.service.ServiceException;
import cgl.narada.service.security.events.TemplateKeyRequest;
import cgl.narada.util.ObjectMarshaller;


public class TestOperations {

  public void testDigest(EntityOperationsImpl entityOperations, 
			 byte[] encryptedBytes, String algorithm) 
    throws ServiceException {
    byte[] digest = 
      entityOperations.generateMessageDigest(encryptedBytes,
					     algorithm);
    boolean digestVerify =
      entityOperations.validateMessageDigest(digest, encryptedBytes,
					     algorithm);
    if (digestVerify) {
      System.out.println("Digest Verification success ...");
    } else {
      System.out.println("Verification unsuccessful");
    }
  }

  public static void main(String[] args) {
    try {
      TestOperations testOps = new TestOperations();
      
      String module = "TestOperations.main()-> ";
      EntityOperationsImpl entityOperations = new EntityOperationsImpl();
      EntityKeyManagementImpl entityKeyMgmtImpl = 
	new EntityKeyManagementImpl();
      
      KeyManagementServiceImpl kms = new KeyManagementServiceImpl();

      String provider="CryptixCrypto";
      String mode = "CBC";
      String padding = "PKCS5Padding";
      
      SecretKey secKey = kms.generateSecretKey("Rijndael", provider);
      
      String testString = "Test String to determine if operations work ";
      byte[] testBytes = testString.getBytes();

      byte[] iv = entityOperations.getIV(secKey, mode, padding, provider);
      
      byte[] encryptedBytes = 
	entityOperations.encryptPayload(secKey, mode, padding, provider,
					testBytes, iv);
      
      System.out.println(module + "Encrypted Payload: Length=" + 
			 encryptedBytes.length + ", Content = " + 
			 new String(encryptedBytes)); 
      byte[] originalBytes = 
	entityOperations.decryptPayload(secKey, mode, padding, provider,
					encryptedBytes, iv);
      System.out.println(module + "Original Payload=" + 
			 new String(originalBytes) );


      testOps.testDigest(entityOperations, encryptedBytes, "SHA-256");


      KeyPair keyPair = 
	entityKeyMgmtImpl.generatePersonalKeyPair("RSA", 2048, 
						  provider, "1234");
      
      byte[] pkEncryptedBytes = 
	entityOperations.encryptPayload(keyPair.getPublic(), "ECB", "PKCS#1", 
					provider, testBytes);
      byte[] pkDecryptedBytes =
	entityOperations.decryptPayload(keyPair.getPrivate(),  "ECB", "PKCS#1", 
					provider, pkEncryptedBytes);
      
      String decryptedString = new String(pkDecryptedBytes);
      System.out.println("Decrypted Message is \n" + decryptedString);

      byte[] pkSignatureBytes = 
	entityOperations.signPayload(keyPair.getPrivate(), "SHA1withRSA", 
				     provider, pkEncryptedBytes);
      boolean verified =
	entityOperations.validateSignature(keyPair.getPublic(), "SHA1withRSA", 
					   provider, pkEncryptedBytes, 
					   pkSignatureBytes  );
      if (verified) {
	System.out.println("Signature Validation Success ...");
      } else {
	System.out.println("Signature NOT Validated ...");
      }
      

      
      KeyStoreManagementImpl ksmi = new KeyStoreManagementImpl();
      String keyStoreFileLocation = "C:/TempFiles/keystores/TemplateKeyStore";
      String keyStoreType = "JCEKS"; 
      String keyStoreProvider = "SunJCE" ;
      char[] keyStorePassword = "password".toCharArray();
      char[] keyEntryPassword = "newpass".toCharArray();

      /*KeyStore keyStore;
	keyStore = ksmi.createKeyStore(keyStoreFileLocation, keyStoreType, 
	keyStoreProvider,  keyStorePassword);
	
	Enumeration e = ksmi.retrieveAliases(keyStore);
	
	while (e.hasMoreElements()) {
	String alias = (String)e.nextElement();
	System.out.println("Alias->" + alias+ " <<>>" + 
	ksmi.retrieveKey(keyStore, alias, keyEntryPassword) );
	}
	
	ksmi.addTemplateKey(12345, keyStore, secKey, keyEntryPassword);
	ksmi.saveKeyStore(keyStore, keyStoreFileLocation, keyStorePassword);
      */
      keyStoreFileLocation = "C:/TempFiles/keystores/PersonalKeyStore";
      KeyStore personalKeyStore = 
	ksmi.createKeyStore(keyStoreFileLocation, keyStoreType, 
			    keyStoreProvider,  keyStorePassword);
      
      ksmi.processPersonalKeyStore(personalKeyStore, "nbKeys", keyStorePassword);
      
      java.security.cert.Certificate cert = 
	personalKeyStore.getCertificate("nbKeys");
      PrivateKey pkey =(PrivateKey) personalKeyStore.getKey("nbKeys", keyStorePassword);
      
      System.out.println(cert + "\n");
      TemplateKeyRequest tkReq = new TemplateKeyRequest(7007, 12345, cert);
      byte[] tkReqBytes = tkReq.getBytes();
      TemplateKeyRequest tkReq2 = new TemplateKeyRequest(tkReqBytes);

      System.out.println(tkReq2.getEntityCertificate());

      byte[] secretKeyBytes = ObjectMarshaller.marshall(secKey);
      
      System.out.println(module + "SecretKey Bytes: Length = " +
			 secretKeyBytes.length);

      //KeyPair keyPair = 
      //entityKeyMgmtImpl.generatePersonalKeyPair("RSA", 1024, provider,
      //1234);

      byte[] pkTKBytes = 
	entityOperations.encryptPayload(keyPair.getPublic(), "ECB", "PKCS#1", 
					provider, secretKeyBytes);
      byte[] pkTKDecBytes =
	entityOperations.decryptPayload(keyPair.getPrivate(), "ECB", "PKCS#1", 
					provider, pkTKBytes);

      System.out.println(module + "Length of encrypted key bytes = " +
			 pkTKBytes.length );
      SecretKey recoverKey = 
	(SecretKey) ObjectMarshaller.unmarshall(pkTKDecBytes);

      


      originalBytes = 
	entityOperations.decryptPayload(recoverKey, mode, padding, provider,
					encryptedBytes, iv);
      System.out.println(module + "Original Payload=" + 
			 new String(originalBytes) );

    } catch (Exception serEx) {
      System.out.println(serEx);
    }
  }

}
